
# GCC工具定义

PREFIX = 

ifdef GCC_PATH
CC = $(GCC_PATH)/$(PREFIX)gcc
AS = $(GCC_PATH)/$(PREFIX)gcc -x assembler-with-cpp
CP = $(GCC_PATH)/$(PREFIX)objcopy
SZ = $(GCC_PATH)/$(PREFIX)size
else
CC = $(PREFIX)gcc
AS = $(PREFIX)gcc -x assembler-with-cpp
CP = $(PREFIX)objcopy
SZ = $(PREFIX)size
endif


# 目标文件名
TARGET = main

# DEBUG选项
DEBUG = 1

# 选择不与-g冲突的优化
OPT = -Og

# 中间文件路径
BUILD_DIR = build

# C源文件
C_SOURCES = 					\
main.c							\

C_SOURCES_FOLDER = 				\
container						\
hj212_client					\
hj212_client/hj212_data_msg		\
hj212_client/hj212_request		\
system

# C全局宏
C_SRC_DEFS = 


# C头文件路径
C_SRC_INCLUDES =				\
container						\
hj212_client					\
system

# 拼接
C_DEFS =  $(patsubst %, -D%, $(C_SRC_DEFS))
C_INCLUDES = $(patsubst %, -I%, $(C_SRC_INCLUDES))
C_SOURCES += $(foreach n, $(C_SOURCES_FOLDER), $(wildcard $(n)/*.c))

CFLAGS = -std=gnu11 $(C_DEFS) $(C_INCLUDES) $(OPT) -Wall -fdata-sections -ffunction-sections

# 添加调试信息编译
ifeq ($(DEBUG), 1)
CFLAGS += -g
endif


CFLAGS += -MMD -MP -MF"$(@:%.o=%.d)"


LDSCRIPT = linkerscript.ld

# LDFLAGS = -T$(LDSCRIPT) -Wl,-Map=$(BUILD_DIR)/$(TARGET).map
LDFLAGS = -Wl,-Map=$(BUILD_DIR)/$(TARGET).map -lws2_32

# all: $(BUILD_DIR)/$(TARGET).exe
all: $(TARGET).exe

OBJECTS = $(addprefix $(BUILD_DIR)/,$(notdir $(C_SOURCES:.c=.o)))
vpath %.c $(sort $(dir $(C_SOURCES)))

$(BUILD_DIR)/%.o: %.c Makefile | $(BUILD_DIR) 
	@echo -e "Compile $<"
	@$(CC) -c $(CFLAGS) -Wa,-a,-ad,-alms=$(BUILD_DIR)/$(notdir $(<:.c=.lst)) $< -o $@

# $(BUILD_DIR)/$(TARGET).exe: $(OBJECTS) Makefile
$(TARGET).exe: $(OBJECTS) Makefile
	@echo -e "Link $@"
	@$(CC) $(OBJECTS) $(LDFLAGS) -o $@
	@echo -e "Size $@"
	@$(SZ) $@

$(BUILD_DIR):
	mkdir $(BUILD_DIR)

# 头文件依赖
-include $(wildcard $(BUILD_DIR)/*.d)

.PHONY:clean	# 清理
.PHONY:src		# 源文件
.PHONY:inc		# 头文件
.PHONY:def		# 全局宏
.PHONY:info		# makefile调试

.PHONY:folder


clean:
	rm -rf build/*
	rm -rf main.exe

src:
	@echo -e "$(patsubst %, \t%\n, $(C_SOURCES))"
inc:
	@echo -e "$(patsubst %, \t%\n, $(C_SRC_INCLUDES))"
def:
	@echo -e "$(patsubst %, \t%\n, $(C_SRC_DEFS))"
folder:
	@echo -e "$(C_SOURCES_FOLDER)"

# @echo -e "$(patsubst %, \t%\n, $(C_SRC_DEFS))"

info:
	@echo -e "C_SOURCES = $(C_SOURCES)"
	@echo -e "DEBUG = $(DEBUG)"
	@echo -e "CFLAGS = $(CFLAGS)"
	@echo -e "CC = $(CC)"
	@echo -e "AS = $(AS)"
	@echo -e "CP = $(CP)"
	@echo -e "SZ = $(SZ)"
